package com.yunshipei.ui.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.yunshipei.base.BaseSubscriberAdapter;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.enterplorer.R;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.SetupPhotoDialog;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.FileUtils;
import com.yunshipei.utils.StringUtil;
import com.yunshipei.utils.ToastUtils;

import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import io.rong.app.DemoContext;
import io.rong.app.model.GroupCreateInfo;
import io.rong.app.utils.StringUtilSub;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Group;

/**
 * Created by cike on 16/8/25.
 */
public class GroupAvatarFragment extends Fragment {
    private static final int PHOTO_REQUEST_CAMERA = 3;        //相机拍照
    private static final int PHOTO_REQUEST_GELLERY = 4;        //图库选择
    private static final int PHOTO_REQUEST_CUT = 5;            //图片裁减
    // 创建一个以当前时间为名称的文件
    File tempFile = null;
    File tempShearFile = null;
    private String imgCachePath = "";
    protected static String PHOTO_FILE_NAME = StringUtilSub.getPhotoFileName();
    private SharedPreferences mySharedPreferences;
    private Bitmap bitmap;

    private ImageView avatorView;
    private TextView nameView;
    private GroupCreateInfo mApiResult;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mySharedPreferences = getActivity().getSharedPreferences("ysp_rongCloud", Activity.MODE_PRIVATE);
        imgCachePath = FileUtils.getEnterImgCachePath();
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.group_avatar_layout, null);
        avatorView = (ImageView) view.findViewById(R.id.group_avatar);
        nameView = (TextView) view.findViewById(R.id.group_main_name);
        avatorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                funcShowClassMenu(v);
            }
        });
//        nameView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (mApiResult != null) {
//                    Log.e("群组名称", mApiResult.getName());
//                    Log.e("群组Id", mApiResult.getId());
//                    Log.e("群组成员", mApiResult.getGourpMembers());
//                    Log.e("我的Id", mySharedPreferences.getString("uuid", ""));
//                } else {
//                    Log.e("mApiResult", "is null");
//                }
//            }
//        });
        return view;
    }

    public void setGroupName(String name) {
        nameView.setText(StringUtilSub.getInstance().SubStringAddCH(0, name, 8));
    }

    private void funcShowClassMenu(View v) {
        final SetupPhotoDialog dialog = DialogHelper.getSetupPhotoDialog(getActivity());
        dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                switch (v.getId()) {
                    case R.id.open_camera:
                        camera();
                        break;
                    case R.id.open_photo:
                        gallery();
                        break;
                }
            }
        });
        dialog.show();
    }

    public void camera() {
        if (BaseUtil.isCameraAvailable()) {
            tempFile = new File(imgCachePath, PHOTO_FILE_NAME);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
            startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
        } else {
            ToastUtils.showToast(R.string.camera_permission_request);
        }
    }

    public void gallery() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, PHOTO_REQUEST_GELLERY);
    }

    public void setmApiResult(GroupCreateInfo mApiResult) {
        this.mApiResult = mApiResult;
        nameView.setText(StringUtilSub.getInstance().SubStringAddCH(0, mApiResult.getName().toString(), 8));
        //加载群头像
        if (!StringUtil.isEmpty(mApiResult.getPortraitUri())) {
            Glide.with(getActivity()).load(mApiResult.getPortraitUri()).into(avatorView);
            avatorView.setTag(mApiResult.getPortraitUri());
        }
    }

    private void crop(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);

        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);

        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDatection", true);
        String fileName = StringUtilSub.getPhotoFileName();
        tempShearFile = new File(imgCachePath, fileName);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempShearFile));
        startActivityForResult(intent, PHOTO_REQUEST_CUT);

    }

    /*
     * 图片压缩
     */
    private Bitmap compressImage(Bitmap image) throws FileNotFoundException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 80, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        File file = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
        FileOutputStream outputStream = new FileOutputStream(file);
        image.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        return BitmapFactory.decodeStream(isBm, null, null);
    }

    public File saveBitmap(Bitmap bm) {
        File f = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        PHOTO_FILE_NAME = StringUtilSub.getPhotoFileName();
        return f;
    }

    /**
     * 图片上传
     * 文件的方式
     *
     * @param file
     */
    public void upload(File file) {
        HttpMethods.getInstance().modifyIMGroupAvatar(mApiResult.getId(), file, new UploadRequestSubscriber());
    }

    private class UploadRequestSubscriber extends BaseSubscriberAdapter<JSONObject> {
        @Override
        public void onNext(JSONObject jsonObject) {
            int status = jsonObject.optInt("status");
            String message = jsonObject.optString("message");
            if (!TextUtils.isEmpty(message))
                ToastUtils.showToast(message);
            if (0 == status) {
                Toast.makeText(getActivity(), "头像上传失败", Toast.LENGTH_SHORT).show();
                return;
            }
            JSONObject dataObj = jsonObject.optJSONObject("data");
            if (dataObj == null) return;
            String avatarUrl = dataObj.optString("avatar");
            Glide.with(getActivity()).load(avatarUrl).dontAnimate().into(avatorView);
            String id = mApiResult.getId();
            mApiResult.setPortraitUri(avatarUrl);
            DemoContext.getInstance(getActivity()).updateGroupInfoById(id, avatarUrl, DemoContext.STATE1);
            refreshGroupInfo(new Group(mApiResult.getId(), mApiResult.getName(), Uri.parse(avatarUrl)));
            tempFile = null;
        }

        @Override
        public void onError(String errorMessage) {
            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 添加了用户缓存更新方法(rongcloud)
     */
    private void refreshGroupInfo(Group group) {

        if (group == null) {
            throw new IllegalArgumentException();
        }

        if (RongIM.getInstance() != null) {
            RongIM.getInstance().refreshGroupInfoCache(group);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_REQUEST_GELLERY) {
            if (data != null) {
                Uri uri = data.getData();
                crop(uri);
            }
        } else if (requestCode == PHOTO_REQUEST_CAMERA) {
            tempFile = new File(imgCachePath, PHOTO_FILE_NAME);
            tempFile.setReadable(true);
            tempFile.setWritable(true);
            if (FileUtils.haveFile(tempFile)) {
                crop(Uri.fromFile(tempFile));
            }
        } else if (requestCode == PHOTO_REQUEST_CUT) {
            if (data == null) return;
            try {
                if (FileUtils.haveFile(tempShearFile)) {
                    bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(Uri.fromFile(tempShearFile)));
                    bitmap = compressImage(bitmap);
                    tempFile = saveBitmap(bitmap);
                    //在这里上传
                    if (tempFile != null) {
                        upload(tempFile);
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
